package com.songcha.sakura.mvvm.home.home


import android.os.Bundle
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.sakura.R
import com.songcha.sakura.ui.adapter.HomeBannerAdapter

import com.songcha.sakura.databinding.FragmentHomeBinding
import com.songcha.sakura.ui.adapter.HomeCateAdapter

import com.songcha.sakura.event.HomeComicGetCompletedEvent
import com.songcha.sakura.ui.adapter.SearchHistoryListAdapter
import com.songcha.sakura.util.*
import com.songcha.library_database_sakura.greendao.SearchHistoryBean
import com.songcha.sakura.ui.base.BaseComicMvvmFragment
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.constants.PageStyle
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


class HomeFragment: BaseComicMvvmFragment<HomeViewModel, FragmentHomeBinding>(),TextView.OnEditorActionListener,View.OnFocusChangeListener {
    companion object{
        val TAG:String=HomeFragment::class.java.simpleName
    }
    private var mPwSearchHistory:PopupWindow?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }


    override fun initView(savedInstanceState: Bundle?){

        EventBus.getDefault().register(this)

        databinding.edtSearch.setOnEditorActionListener(this)
        databinding.edtSearch.setOnFocusChangeListener(this)

        val vp=databinding.vp
        vp.adapter=HomeCateAdapter(childFragmentManager,viewModel.cateTitles)
        vp.offscreenPageLimit=2
        databinding.ctl.setViewPager(vp)

        databinding.bvp.apply {
            adapter = HomeBannerAdapter(context) as BaseBannerAdapter<Any>
            setPageStyle(PageStyle.MULTI_PAGE_SCALE)
            setRevealWidth(20.dp2px())
            setIndicatorSliderColor(ColorUtil.getResourceColor(context,R.color.half_black),ColorUtil.getResourceColor(context,R.color.primary))
            registerLifecycleObserver(lifecycle)
        }.create()

        viewModel.getBannerList()
        viewModel.bannerList.observe(viewLifecycleOwner){
            databinding.bvp.refreshData(it.data)
        }

        viewModel.searchHistoryList.observe(viewLifecycleOwner){
            showSearchHistory(it)
        }

    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }


    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

        if(actionId==EditorInfo.IME_ACTION_SEARCH){
            val key=databinding.edtSearch.text.toString()
            if(key.isNullOrBlank()){
                ToastUtil.show("请输入搜索关键字")
                return false
            }

            mPwSearchHistory?.dismiss()
            databinding.edtSearch.clearFocus()

            mPwSearchHistory?.setOnDismissListener {
                MyJumpUtil.toSearchComic(requireContext(),key)
            }

            MyJumpUtil.toSearchComic(requireContext(),key)

            return true
        }
        return false
    }


    @Subscribe
    fun onHomeComicGetCompleted(event:HomeComicGetCompletedEvent){
       viewModel.updateHomeCache(event)
    }

   /* @Subscribe
    fun onHomeScheduleGetCompleted(event: HomeScheduleEvent){
        viewModel.getBannerList(event.data)
    }*/


    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        if(v==null) return
        if(v.id==databinding.edtSearch.id && hasFocus){
            viewModel.getSearchHistory()
        }else{
            mPwSearchHistory?.dismiss()
        }
    }

    fun showSearchHistory(list:MutableList<SearchHistoryBean>){
        val view=layoutInflater.inflate(R.layout.pop_search_history,null)
        val rcv=view.findViewById<RecyclerView>(R.id.rcv_history)
        rcv.apply {
            layoutManager=LinearLayoutManager(requireContext())
            adapter=SearchHistoryListAdapter(requireContext(),list).apply {
                setOnItemClickListener{a,v,p->
                    mPwSearchHistory?.setOnDismissListener {
                        MyJumpUtil.toSearchComic(requireContext(),list[p].title)
                    }

                    mPwSearchHistory?.dismiss()
                    databinding.edtSearch.clearFocus()
                }
            }
        }

        mPwSearchHistory=PopupWindow(view)
        mPwSearchHistory!!.width=ViewGroup.LayoutParams.MATCH_PARENT
        mPwSearchHistory!!.height=200.dp2px()
        mPwSearchHistory!!.animationStyle=(com.songcha.library_common.R.style.dialogTopSlideWindowAnim)
        mPwSearchHistory!!.showAsDropDown(databinding.edtSearch,0,5.dp2px())
    }


}